require 'monitor'
require 'webrick'
include WEBrick

require 'shard_servlet.rb'

$DOC_ROOT = Dir.pwd


server = HTTPServer.new(
  :Port => 8001,
  :DocumentRoot => $DOC_ROOT
)

# ConditionVariable ぽいこともやっちゃってる...
# 以下の変更がきいてくるのは，start のあと
class << server
  def add_to_waiters(thread)
    @lock.synchronize {
      @waiters << thread if not @waiters.include?(thread)
    }
  end

  def remove_from_waiters(thread)
    @lock.synchronize { @waiters.delete(thread) }
  end

  def wakeup_waiters
    @lock.synchronize {
      @waiters.each {|th| th.run }
    }
  end

  def start(&block)
    @waiters = []
    @lock = Monitor.new
    super
  end

  def shutdown
    @lock.synchronize {
      @waiters.each {|th|
        th[:CloseServerRequired] = true
        th.run
      }
    }
    super
  end
end

ShardServlet.set_docroot($DOC_ROOT)
server.mount('/shard', ShardServlet)

['INT', 'TERM'].each {|s|
  Signal.trap(s) { server.shutdown }
}

server.start
